package com.example;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//             req.getRequestDispatcher("limit?page=1").forward(req,resp);
@WebFilter("/limit?page=1")
public class LoginListener implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化监听器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转为HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        //获取session && 判断user是否登陆过
        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("user");
        if (user != null){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            //重新回到登陆界面
            request.getRequestDispatcher("index.jsp").forward(request,servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("结束监听器");
    }
}
